package simpleSpring.spring;

import java.beans.Introspector;
import java.io.File;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author caihe
 * @date 2022/10/24 13:39
 */
public class CaiheApplicationContext {

    private Class clazz;

    private ConcurrentHashMap<String, BeanDefinition> beanDefinitionMap = new ConcurrentHashMap<>();

    private ConcurrentHashMap<String, Object> singletonObjectMap = new ConcurrentHashMap<>();

    private List<BeanPostProcessor> beanPostProcessorList = new ArrayList<>();

    public CaiheApplicationContext(Class clazz) {
        this.clazz = clazz;
        // 扫描 --> BeanDefinition --> BeanDefinitionMap   通过配置类获取需要扫描的路径 
        if (clazz.isAnnotationPresent(ComponentScan.class)) {
            ComponentScan componentScan = (ComponentScan) clazz.getAnnotation(ComponentScan.class);
            String path = componentScan.value();
            // 替换为文件目录路径
            path = path.replace(".", "/");
            ClassLoader classLoader = CaiheApplicationContext.class.getClassLoader();
            URL resource = classLoader.getResource(path);
            File file = new File(resource.getFile());
            // 路径指向的是文件夹
            if (file.isDirectory()) {
                File[] files = file.listFiles();
                for (File f : files) {
                    String fileName = f.getAbsolutePath();
                    // 找到class文件
                    if (fileName.endsWith(".class")) {
                        try {
                            String className = fileName.substring(fileName.indexOf("simpleSpring"), fileName.lastIndexOf(".class"));
                            className = className.replace("\\", ".");
                            Class<?> loadClass = classLoader.loadClass(className);
                            if (loadClass.isAnnotationPresent(Component.class)) {

                                // 把所有的BeanPostProcessor保存到list中
                                if (BeanPostProcessor.class.isAssignableFrom(loadClass)) {
                                    BeanPostProcessor instance = (BeanPostProcessor) loadClass.newInstance();
                                    beanPostProcessorList.add(instance);
                                }

                                // Bean的名字
                                Component component = loadClass.getAnnotation(Component.class);
                                String beanName = component.value();
                                if ("".equals(beanName)) {
                                    // 默认Bean的名字为类名首字母小写
                                    beanName = Introspector.decapitalize(loadClass.getSimpleName());
                                }

                                // 找到需要注入的Bean 并 定义BeanDefinition
                                BeanDefinition beanDefinition = new BeanDefinition();
                                beanDefinition.setType(loadClass);

                                if (loadClass.isAnnotationPresent(Scope.class)) {
                                    // 是否指定bean的范围
                                    Scope annotation = loadClass.getAnnotation(Scope.class);
                                    beanDefinition.setScope(annotation.value());
                                } else {
                                    // 默认单例
                                    beanDefinition.setScope(Scope.SCOPE_SINGLETON);
                                }
                                beanDefinitionMap.put(beanName, beanDefinition);
                            }
                        } catch (ClassNotFoundException e) {
                            e.printStackTrace();
                        } catch (InstantiationException e) {
                            e.printStackTrace();
                        } catch (IllegalAccessException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }

        // 实例化单例Bean  检查扫描后的beanDefinition有多少单例Bean
        for (String beanName : beanDefinitionMap.keySet()) {
            BeanDefinition beanDefinition = beanDefinitionMap.get(beanName);
            // 如果单例
            if (Scope.SCOPE_SINGLETON.equals(beanDefinition.getScope())) {
                singletonObjectMap.put(beanName, createBean(beanName, beanDefinition));
            }
        }
    }

    private Object createBean(String beanName, BeanDefinition beanDefinition) {

        Class clazz = beanDefinition.getType();

        try {
            // 1、实例化
            Object instance = clazz.getConstructor().newInstance();

            // 2、属性注入
            // 拿到类的所有属性
            Field[] declaredFields = clazz.getDeclaredFields();
            for (Field field : declaredFields) {
                // 判断类的属性是否需要被注入
                if (field.isAnnotationPresent(Autowired.class)) {
                    field.setAccessible(true);
                    // 给field属性赋值
                    field.set(instance, getBean(field.getName()));
                }
            }

            // 3、初始化  initializeBean，aware，initMethod、aop代理
            // Aware回调 查看类有没有实现各种Aware接口
            if (instance instanceof BeanNameAware) {
                ((BeanNameAware) instance).setBeanName(beanName);
            }

            for (BeanPostProcessor beanPostProcessor : beanPostProcessorList) {
                instance = beanPostProcessor.postProcessBeforeInitialization(beanName, instance);
            }
            
            // 初始化
            if (instance instanceof InitializingBean) {
                ((InitializingBean) instance).afterPropertiesSet();
            }

            for (BeanPostProcessor beanPostProcessor : beanPostProcessorList) {
                instance = beanPostProcessor.postProcessAfterInitialization(beanName, instance);
            }
            

            return instance;
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        }
        return null;
    }

    public Object getBean(String beanName) {

        BeanDefinition beanDefinition = beanDefinitionMap.get(beanName);
        if (beanDefinition == null) {
            throw new NullPointerException();
        } else {
            String scope = beanDefinition.getScope();
            if (scope.equals(Scope.SCOPE_SINGLETON)) {
                // 从单例池里面
                Object bean = singletonObjectMap.get(beanName);
                if (bean == null) {
                    bean = createBean(beanName, beanDefinition);
                    singletonObjectMap.put(beanName, bean);
                }
                return bean;
            } else {
                return createBean(beanName, beanDefinition);
            }
        }
    }

}
